<?php
namespace common\service;
use common\models\trade\TradeRechargeModel;
use Yii;
use common\models\TradeRecharge;
use common\models\Member;
use common\utils\CommonFun;

use xtype\Ethereum\Client;

/*
	充值业务
*/

class RechargeService
{



	/*
		充值配置信息
		b_type
		member_id 会员id
		address 钱包地址
		private_key 
	*/
	public static function conf($params)
	{
		$where = ['b_type' => $params['b_type']];
		$conf = TradeRecharge::getOne($where);
		if(!$conf) return ['state' => false, 'msg' => '配置有误'];

		if($conf['type'] == 1)
		{
			//链上充值
			$address = self::getAddress($params,$conf);
			if(!$address) return ['state' => false, 'msg' => '地址生成失败'];
			$conf['address'] = $address;
			$conf['qr_code'] = 'http://qr.topscan.com/api.php?text='.$address;
		}

		return ['state' => true, 'data' => $conf];

	}

	## 获取钱包地址
	private static function getAddress($params,$conf)
	{
		if($params['address'] && $params['private_key']) return $params['address'];

		//生成钱包地址
		$client = new Client(Yii::$app->params['eth']['infuraUrl']);
		list($address, $privateKey) = $client->newAccount();
		CommonFun::writeLog('address:'.$address.', key:'.$privateKey,'address'); 
        //将私钥 加密保存
        $privateKey = CommonFun::encrypt($privateKey);		
        //保存到数据库
        if($address && $privateKey){
            $data = array('address' => $address, 'private_key' => $privateKey);
            $flag = Member::updateAll($data, ['member_id' => $params['member_id']]);
            if($flag) return $address;	            	
        }else{
        	return false;
        }	            		
				
	}



}